package com.niguang.labour.admin.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.niguang.labour.admin.entity.WorkAppUser;
import com.niguang.labour.admin.service.WorkAppUserService;
import com.niguang.labour.admin.vo.IcCardSearchVo;
import com.niguang.labour.common.pojo.Result;
import com.niguang.labour.common.util.ApiTokenUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 'work.v_personSite' is not BASE TABLE 前端控制器
 * </p>
 *
 * @author
 * @since 2018-06-10
 */
@RestController
@RequestMapping("/appUsers")
public class WorkAppUserController {

    @Autowired
    private WorkAppUserService appUserService;

    @Autowired
    private ApiTokenUtils tokenUtils;


    @GetMapping("/search")
    public Result search(String phone, String icCard) {
        if (StringUtils.isBlank(phone) && StringUtils.isBlank(icCard)) {
            return Result.failed("电话号码或ic卡不能同时为空");
        }
        List<IcCardSearchVo> searchVo = appUserService.getIcCardUsers(phone, icCard, tokenUtils.getLaborId());
        if (CollectionUtils.isEmpty(searchVo)) {
            if (StringUtils.isNotBlank(phone) ) {
                return Result.failed("用户未加入班组");
            }
            if (StringUtils.isNotBlank(icCard)) {
                return Result.failed("卡片未绑定用户");
            }
            return Result.failed("没有数据");
        }
        return Result.success(searchVo);
    }


    @PostMapping("/bindIcCard")
    public Result bindIcCard(Long userId, String icCard) {
        WorkAppUser appUser = appUserService.selectOne(new EntityWrapper<WorkAppUser>().eq(WorkAppUser.IC_CARD, icCard));
        if (appUser != null) {
            return Result.failed("该卡号已被绑定");
        }
        final WorkAppUser workAppUser = appUserService.selectById(userId);
        if (workAppUser == null) {
            return Result.failed("没有该用户");
        }
        workAppUser.setIcCard(icCard);
        return Result.success(workAppUser.updateById());
    }


    @PostMapping("/unbindIcCard")
    public Result unbindIcCard(String icCard) {
        WorkAppUser workAppUser = appUserService.selectOne(new EntityWrapper<WorkAppUser>().eq(WorkAppUser.IC_CARD, icCard));
        if (workAppUser == null) {
            return Result.failed("没有该卡号");
        }
        workAppUser.setIcCard("");
        return Result.success(workAppUser.updateById());
    }
}
